package cn.iocoder.yudao.module.expert.controller.admin.extractinfo;

import org.apache.ibatis.executor.BatchResult;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.expert.controller.admin.extractinfo.vo.*;
import cn.iocoder.yudao.module.expert.dal.dataobject.extractinfo.ExtractInfoDO;
import cn.iocoder.yudao.module.expert.service.extractinfo.ExtractInfoService;

@Tag(name = "管理后台 - 抽签结果")
@RestController
@RequestMapping("/expert/extract-info")
@Validated
public class ExtractInfoController {

    @Resource
    private ExtractInfoService extractInfoService;

    @PostMapping("/create")
    @Operation(summary = "创建抽签结果")
    @PreAuthorize("@ss.hasPermission('expert:extract-info:create')")
    public CommonResult<Long> createExtractInfo(@Valid @RequestBody ExtractInfoSaveReqVO createReqVO) {
        return success(extractInfoService.createExtractInfo(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新抽签结果")
    @PreAuthorize("@ss.hasPermission('expert:extract-info:update')")
    public CommonResult<Boolean> updateExtractInfo(@Valid @RequestBody ExtractInfoSaveReqVO updateReqVO) {
        extractInfoService.updateExtractInfo(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除抽签结果")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('expert:extract-info:delete')")
    public CommonResult<Boolean> deleteExtractInfo(@RequestParam("id") Long id) {
        extractInfoService.deleteExtractInfo(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得抽签结果")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('expert:extract-info:query')")
    public CommonResult<ExtractInfoRespVO> getExtractInfo(@RequestParam("id") Long id) {
        ExtractInfoDO extractInfo = extractInfoService.getExtractInfo(id);
        return success(BeanUtils.toBean(extractInfo, ExtractInfoRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得抽签结果分页")
    @PreAuthorize("@ss.hasPermission('expert:extract-info:query')")
    public CommonResult<PageResult<ExtractInfoRespVO>> getExtractInfoPage(@Valid ExtractInfoPageReqVO pageReqVO) {
        PageResult<ExtractInfoDO> pageResult = extractInfoService.getExtractInfoPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, ExtractInfoRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出抽签结果 Excel")
    @PreAuthorize("@ss.hasPermission('expert:extract-info:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportExtractInfoExcel(@Valid ExtractInfoPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        String currentTime = LocalDateTime.now()
                .format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒"));
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ExtractInfoDO> list = extractInfoService.getExtractInfoPage(pageReqVO).getList();
        List<ExtractInfoExcelRespVO> respVOSList = BeanUtils.toBean(list, ExtractInfoExcelRespVO.class);

        Map<String, List<ExtractInfoExcelRespVO>> groupedByProject =respVOSList.stream().collect(Collectors.groupingBy(ExtractInfoExcelRespVO::getProjectName));
        Set<String> keys = groupedByProject.keySet();
        for(String key:keys) {
            for (int i = 0; i < groupedByProject.get(key).size(); i++) {
                 ExtractInfoExcelRespVO respVO = groupedByProject.get(key).get(i);
                respVO.setIndex(i + 1);
                respVO.setBatchNum("第" + respVO.getExtractBatchNum() + "轮");
            }
        }
        // 导出 Excel
        ExcelUtils.writes(response, "抽签结果.xls", ExtractInfoExcelRespVO.class,
                groupedByProject,currentTime);
    }

}